package com.camera2.activity;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.camera2.frament.Frament;
import com.camera2.frament.FramentExpert;
import com.camera2.http.Login;
import com.camera2.local.SharedPrefer;

import java.util.ArrayList;
import java.util.List;


public class ActivityLogin extends Activity {

    private EditText et_id;
    private EditText et_key;
    private Spinner spinner;

    private String id, password;
    private List<String> data_list;
    private ArrayAdapter<String> arr_adapter;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String info = (String) msg.obj;

                    if (info.equals("success")) {
                        try {
                            SharedPrefer.Saveid(getApplicationContext(), id);
                            SharedPrefer.SavePassword(getApplicationContext(), password);
                            int k = SharedPrefer.ReadUserExpert(getApplicationContext());
                            if (k == 0) {
                                finish();
                                startActivity(new Intent(ActivityLogin.this, Frament.class));
                            }
                            if (k == 1) {
                                finish();
                                startActivity(new Intent(ActivityLogin.this, FramentExpert.class));
                            }
                        } catch (Exception e2) {
                            e2.printStackTrace();
                        }

                    } else if (info.equals("用户不存在")) {
                        Toast.makeText(getApplicationContext(), "用户名或密码错误，请重试", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "连接网络失败,请检查网络是否连接", Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_login);
        et_id = findViewById(R.id.et_id);
        et_key = findViewById(R.id.et_key);

        id = SharedPrefer.Readid(getApplicationContext());
        password = SharedPrefer.ReadPassword(getApplicationContext());
        if (id.equals("")) {
        } else {
            et_id.setText(id);
            et_key.setText(password);
        }
        checkGps();

        spinner = findViewById(R.id.spinner);

        data_list = new ArrayList<String>();
        data_list.add("牧民版");
        data_list.add("专家版");

        arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arr_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int positions, long id) {
                SharedPrefer.SaveUserExpert(getApplicationContext(), positions);
//                String str = parent.getItemAtPosition(positions).toString();
//                Toast.makeText(ActivityLogin.this, "你点击的是:" + str, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
    }


    private void checkGps() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO};
        boolean c1 = checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        boolean c2 = checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        boolean c3 = checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean c4 = checkPermission(Manifest.permission.CAMERA);
        if (c1 && c2 && c3 && c4) {
//            if (!username.equals("") && !password.equals("")) {
//                login();
//            }
        } else {
            getPermission(Manifest.permission.READ_EXTERNAL_STORAGE, permissions);
        }
    }

    public boolean checkPermission(String permission) {
        if (ActivityCompat.checkSelfPermission(this, permission)
                == PackageManager.PERMISSION_GRANTED)
            return true;
        else
            return false;
    }

    public void getPermission(String permission, String[] permissions) {
        ActivityCompat.requestPermissions(this, permissions, 1);
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission))
            Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();

    }

    public void ForgetPassword(View view) {
        Intent intent = new Intent(this, LoginForgot.class);
        startActivity(intent);
    }

    public void NewRegister(View view) {
        Intent intent = new Intent(this, LoginRegister.class);
        startActivity(intent);
    }

    public void login(View view) {
        id = et_id.getText().toString();
        password = et_key.getText().toString();
        if (id.equals("") || password.equals(""))
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        else
            login();
    }

    public void login() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String log = Login.login(getApplicationContext(), id, password);
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = log;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);
                }

            }
        }).start();

    }


}
